package com.coffeeloversupportlibrary.coffeelover.mercury.game;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.coffeeloversupportlibrary.R;
import com.coffeeloversupportlibrary.coffeelover.mercury.entity.Game;
import com.coffeeloversupportlibrary.coffeelover.mercury.entity.User;
import com.coffeeloversupportlibrary.coffeelover.mercury.utils.HttpUtils;
import com.coffeeloversupportlibrary.coffeelover.mercury.utils.JsonUtils;
import com.liys.view.LineProView;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @author 盛守义
 * @createTime 2021/11/26 21:36
 * @projectName TurningCoffee
 * @className FirstStageActivity.java
 * @description TODO
 */
public class FirstStageActivity extends AppCompatActivity {
    private SharedPreferences userInfo;
    private Activity activity = FirstStageActivity.this;
    private User user;
    private Game game;

    private ImageView iv_plant;
    private TextView tv_username, tv_coffeename, tv_introduce, tv_totalwater, tv_grade;
    private LineProView tv_bar;
    private ImageView iv_towBar;
    private FrameLayout fl_water;

    private HttpUtils httpUtils = new HttpUtils();
    private JsonUtils jsonUtils = new JsonUtils();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game_activity_shoot);

        initView();
        setListener();
        setView();
    }

    void setView(){
        tv_username.setText(user.getData().getUser().getUserNickname());
        tv_coffeename.setText(game.getData().getTree().getTreeName());
        tv_totalwater.setText(""+game.getData().getTree().getUserWater());


        int status = game.getData().getTree().getTreeStatus();
        if(status == 0){
            double proportion = (double) ((30-game.getData().getTree().getTreeWater())/0.3);
            tv_introduce.setText("阿拉比卡豆再浇水"+ String.format("%.2f", proportion) +"%嫩芽就长高啦! ");
            tv_bar.setProgress(game.getData().getTree().getTreeWater()/0.3);
            tv_grade.setText("1级");

            iv_plant.setImageResource(R.drawable.shoot);
        }else if (status == 1){
            double proportion = (double) ((60-game.getData().getTree().getTreeWater())/0.3);
            tv_introduce.setText("阿拉比卡豆再浇水"+ String.format("%.2f", proportion) +"%嫩芽就长高啦! ");
            tv_bar.setProgress((game.getData().getTree().getTreeWater()-30)/0.3);
            tv_grade.setText("2级");

            iv_plant.setImageResource(R.drawable.atree);
        }else{
            double proportion = (double) ((100-game.getData().getTree().getTreeWater())/0.4);
            tv_introduce.setText("阿拉比卡豆再浇水"+ String.format("%.2f", proportion) +"%嫩芽就长高啦! ");
            tv_bar.setProgress((game.getData().getTree().getTreeWater()-60)/0.4);
            tv_grade.setText("3级");

            iv_plant.setImageResource(R.drawable.beans);
        }
//        ViewGroup.LayoutParams params = tv_bar.getLayoutParams();
//        params.width = (maxWidth/3)*(game.getData().getTree().getTreeWater()/10);
//        tv_bar.setLayoutParams(params);
    }

    void setListener(){
        ShootOnClickListener listener = new ShootOnClickListener();
        iv_towBar.setOnClickListener(listener);
        fl_water.setOnClickListener(listener);
    }

    void initView(){
        userInfo = getSharedPreferences("user", 0);
        user = jsonUtils.getUser(userInfo.getString("userInfo", ""));
        game = jsonUtils.getGame(userInfo.getString("tree", ""));

        tv_totalwater = findViewById(R.id.tv_totalwater);
        tv_coffeename = findViewById(R.id.tv_snamegs);
        tv_username = findViewById(R.id.tv_unamegs);
        tv_introduce = findViewById(R.id.tv_introducegs);
        tv_bar = findViewById(R.id.tv_bargs);

        tv_grade = findViewById(R.id.tv_gradegs);
        iv_plant = findViewById(R.id.iv_plant);
        fl_water = findViewById(R.id.fl_water);
        iv_towBar = findViewById(R.id.iv_towatergs);

    }

    void WaterTree(){
        Call call = httpUtils.getCall("/tree/water/"+game.getData().getTree().getId());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, "网络连接崩溃了，绝对绝对不是我们的错", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String res = response.body().string();
                Log.e("浇水", "onResponse: "+res);
                Game waterGame = jsonUtils.getGame(res);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SharedPreferences.Editor editor = userInfo.edit();
                        editor.putString("tree", res);
                        editor.commit();

                        ValueAnimator animator = ValueAnimator.ofFloat(0f, (float)(10/0.3));
                        animator.setDuration(500);
                        animator.setInterpolator(new AccelerateDecelerateInterpolator());
                        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator animation) {
                                if (game.getData().getTree().getTreeWater() == 0){
                                    tv_bar.setProgress((float)animation.getAnimatedValue());
                                }else{
                                    tv_bar.setProgress((game.getData().getTree().getTreeWater()-10)/0.3 + (float)animation.getAnimatedValue());
                                }
                            }
                        });
                        animator.start();
                        //动画结束后，将值固定
                        game = waterGame;

                        tv_totalwater.setText(""+waterGame.getData().getTree().getUserWater());
                        float waterproportion = (float) ((30-waterGame.getData().getTree().getTreeWater())/0.3);
                        tv_introduce.setText("阿拉比卡豆再浇水"+ String.format("%.2f", waterproportion) +"%嫩芽就长高啦! ");
                        if(waterGame.getData().getTree().getTreeStatus() == 1){
                            tv_grade.setText("2级");
                            ValueAnimator animator1 = ValueAnimator.ofFloat(0f, 0f);
                            animator.setDuration(100);
                            animator.setInterpolator(new AccelerateDecelerateInterpolator());
                            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                @Override
                                public void onAnimationUpdate(ValueAnimator animation) {
                                    tv_bar.setProgress((float)animator1.getAnimatedValue());
                                }
                            });
                            animator.start();
                            tv_introduce.setText("开始给树苗浇水吧");
                            iv_plant.setImageResource(R.drawable.atree);
                        }

                    }
                });
            }
        });
    }

    void WaterTree2(){
        Call call = httpUtils.getCall("/tree/water/"+game.getData().getTree().getId());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, "网络连接崩溃了，绝对绝对不是我们的错", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String res = response.body().string();
                Log.e("浇水", "onResponse: "+res);
                Game waterGame = jsonUtils.getGame(res);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SharedPreferences.Editor editor = userInfo.edit();
                        editor.putString("tree", res);
                        editor.commit();

                        ValueAnimator animator = ValueAnimator.ofFloat(0f, (float)(10/0.3));
                        animator.setDuration(500);
                        animator.setInterpolator(new AccelerateDecelerateInterpolator());
                        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator animation) {
                                if (game.getData().getTree().getTreeWater() == 30){
                                    tv_bar.setProgress((float)animation.getAnimatedValue());
                                }else{
                                    tv_bar.setProgress((game.getData().getTree().getTreeWater()-40)/0.3 + (float)animation.getAnimatedValue());
                                }
                            }
                        });
                        animator.start();
                        //动画结束后，将值固定
                        game = waterGame;

                        tv_totalwater.setText(""+waterGame.getData().getTree().getUserWater());
                        float waterproportion = (float) ((60-waterGame.getData().getTree().getTreeWater())/0.3);
                        tv_introduce.setText("阿拉比卡豆再浇水"+ String.format("%.2f", waterproportion) +"%嫩芽就长高啦! ");
                        if(waterGame.getData().getTree().getTreeStatus() == 2){
                            tv_grade.setText("3级");
                            ValueAnimator animator1 = ValueAnimator.ofFloat(0f, 0f);
                            animator.setDuration(100);
                            animator.setInterpolator(new AccelerateDecelerateInterpolator());
                            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                @Override
                                public void onAnimationUpdate(ValueAnimator animation) {
                                    tv_bar.setProgress((float)animator1.getAnimatedValue());
                                }
                            });
                            animator.start();
                            tv_introduce.setText("开始给树苗浇水吧");
                            iv_plant.setImageResource(R.drawable.beans);

                        }

                    }
                });
            }
        });
    }

    void WaterTree3(){
        Call call = httpUtils.getCall("/tree/water/"+game.getData().getTree().getId());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, "网络连接崩溃了，绝对绝对不是我们的错", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String res = response.body().string();
                Log.e("浇水", "onResponse: "+res);
                Game waterGame = jsonUtils.getGame(res);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SharedPreferences.Editor editor = userInfo.edit();
                        editor.putString("tree", res);
                        editor.commit();

                        ValueAnimator animator = ValueAnimator.ofFloat(0f, (float)(10/0.4));
                        animator.setDuration(500);
                        animator.setInterpolator(new AccelerateDecelerateInterpolator());
                        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator animation) {
                                if (game.getData().getTree().getTreeWater() == 60){
                                    tv_bar.setProgress((float)animation.getAnimatedValue());
                                }else{
                                    tv_bar.setProgress((game.getData().getTree().getTreeWater()-70)/0.4 + (float)animation.getAnimatedValue());
                                }
                            }
                        });
                        animator.start();
                        //动画结束后，将值固定
                        game = waterGame;

                        tv_totalwater.setText(""+waterGame.getData().getTree().getUserWater());
                        float waterproportion = (float) ((100-waterGame.getData().getTree().getTreeWater())/0.4);
                        tv_introduce.setText("阿拉比卡豆再浇水"+ String.format("%.2f", waterproportion) +"%嫩芽就长高啦! ");
                        if(waterGame.getData().getTree().getTreeStatus() == 0){
                            AlertDialog alertDialog = new AlertDialog.Builder(activity)
                                    .setTitle("恭喜").setMessage("您获得了 "+(int)(1+Math.random()*10)+" 颗咖啡豆，可在商城兑换商品")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            setView();
                                        }
                                    })
                                    .create();
                            alertDialog.show();
                        }

                    }
                });
            }
        });
    }

    class ShootOnClickListener implements View.OnClickListener{
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.iv_towatergs:
                    startActivity(new Intent(activity, GetWaterBarActivity.class));
                    break;
                case R.id.fl_water:
                    game = jsonUtils.getGame(userInfo.getString("tree", ""));
                    if(game.getData().getTree().getUserWater() >= 10){
                        switch (game.getData().getTree().getTreeStatus()){
                            case 0:
                                WaterTree();
                                break;
                            case 1:
                                WaterTree2();
                                break;
                            case 2:
                                WaterTree3();
                                break;
                        }

                    }else{
                        Toast.makeText(activity, "您的水滴不足，快去领取水滴吧", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("返回时运行", "onResume: 返回了");
        game = jsonUtils.getGame(userInfo.getString("tree", ""));
        tv_totalwater.setText(""+game.getData().getTree().getUserWater());
    }
}
